package com.za.apm.cat.action;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Transaction;

/**
 * Servlet implementation class ApmServlet
 */
public class ApmServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public ApmServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		String pageName = "ApmServlet";
		String serverIp = "127.0.0.1";
		double amount = 0;
		Transaction trans = Cat.newTransaction("MyURL", pageName);
		int status = Math.abs(new Random().nextInt()) % 3;
		try {
			Cat.getProducer().logEvent("MyURL.Server2", serverIp, Event.SUCCESS, "ip=" + serverIp + "&...");
			Cat.logMetricForCount("PayCount");
			Cat.logMetricForSum("PayAmount", amount);
			//System.out.println("status:" + status);
			if (status == 0) {
				System.out.println(1 / 0);
			}
			if (status == 1) {
				System.out.println("---执行慢---");
				TimeUnit.SECONDS.sleep(5);
			}
			if (status == 2) {
				System.out.println("===正常执行===");
			}
			trans.setStatus(Transaction.SUCCESS);
		} catch (Exception e) {
			Cat.getProducer().logError(e);
			System.out.println("出错：" + e.getMessage());
			trans.setStatus(e);
		} finally {
			trans.complete();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
